package com.example.loginproject.view.views

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import com.example.loginproject.tool.dp2px
import com.example.loginproject.tool.getMode
import com.example.loginproject.tool.getSize

class TextDrawView(context:Context,attrs:AttributeSet?):View(context,attrs) {
    private var mPath1 = Path()
    private var mPath2 = Path()

    private val mPaint = Paint().apply {
        color = Color.BLUE
        strokeWidth = (context.dp2px(3)).toFloat()
        style = Paint.Style.FILL_AND_STROKE
        isAntiAlias = true
    }
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        var mWidth = 0
        var mHeight = 0
        mWidth = when(getMode(widthMeasureSpec)){
            MeasureSpec.EXACTLY -> getSize(widthMeasureSpec)
            else -> context.dp2px(160)
        }
        mHeight = when(getMode(heightMeasureSpec)){
            MeasureSpec.EXACTLY -> getSize(heightMeasureSpec)
            else ->  context.dp2px(200)
        }
        setMeasuredDimension(mWidth,mHeight)
    }
    private var mCubicHeight1 = context.dp2px(100).toFloat()
    private var mCubicHeight2 = context.dp2px(100).toFloat()
    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event?.action == MotionEvent.ACTION_DOWN) {
            ValueAnimator.ofFloat(context.dp2px(100).toFloat(), -context.dp2px(100).toFloat())
                .apply {
                    repeatCount =ValueAnimator.INFINITE
                    repeatMode = ValueAnimator.REVERSE
                    duration = 1000
                    addUpdateListener {
                        mCubicHeight1 = it.animatedValue as Float
                        invalidate()
                    }
                    this.start()
                }
        }
        return true
    }
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        mPath1.reset()
        mPath2.reset()
        mPath1.moveTo(0f,height.toFloat()/2)
        mPath2.moveTo(0f,height.toFloat()/2)
        mPath1.cubicTo(  width.toFloat()/2,
            height.toFloat()/2 - mCubicHeight1,
            width.toFloat()/2 + mCubicHeight1,
            height.toFloat()/2 + mCubicHeight1,
               width.toFloat(),
            height.toFloat()/2)

        mPath2.cubicTo(  width.toFloat()/2,
            height.toFloat()/2 + mCubicHeight2,
            width.toFloat()/2 ,
            height.toFloat()/2 + mCubicHeight2,
             width.toFloat() ,
            height.toFloat()/2)
        canvas.drawPath(mPath1,mPaint)
        canvas.drawPath(mPath2,mPaint)
    }
}